import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class FooBar {

    public static FooBar fooBar;

    private int n;

    volatile int flag=0;

    Lock lock;

    Condition cd1,cd2;

    public FooBar(int n) {
        this.n = n;
        this.lock=new ReentrantLock();
        this.cd1=lock.newCondition();
        this.cd2=lock.newCondition();
    }

    public void foo(Runnable printFoo) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            lock.lock();
            try {
                while(flag!=0){
                    this.cd1.await();
                }
                // printFoo.run() outputs "foo". Do not change or remove this line.
                printFoo.run();
                flag=1;
                cd2.signal();
            }
            catch (Exception e){
            }
            finally {
                lock.unlock();
            }
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            lock.lock();
            try {
                while(flag!=1){
                    this.cd2.await();
                }
                // printBar.run() outputs "bar". Do not change or remove this line.
                printBar.run();
                flag=0;
                cd1.signal();
            }
            catch (Exception e){
            }
            finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        FooBar.fooBar=new FooBar(10);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    fooBar.bar(new Runnable() {
                        @Override
                        public void run() {
                            System.out.println("bar");
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    fooBar.foo(new Runnable() {
                        @Override
                        public void run() {
                            System.out.println("foo");
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}